package com.epam.ws.anatomist.common;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.epam.ws.anatomist.common.exception.ConfigurationCreationException;
import com.epam.ws.anatomist.common.exception.ErrorMessages;
import com.epam.ws.anatomist.message.TemplateEntity;
import com.epam.ws.anatomist.message.TemplatePojoEntity;

/**
 * @author Aliaksandr Khachaturan
 *
 */
public class ApplicationStorage
{
	private ApplicationContext context;

	private static final Logger LOGGER = Logger.getLogger(ApplicationStorage.class);

	private static final String CREATE_MESSAGE = "Create ApplicationStorage for configPath=%s";

	private ApplicationStorage()
	{
	}

	public static ApplicationStorage newInstance(String configPath)
	{
		if (configPath == null || configPath.isEmpty())
		{
			LOGGER.error(ErrorMessages.CONFIG_PATH_EMPTY_ERROR);
			throw new ConfigurationCreationException(ErrorMessages.CONFIG_PATH_EMPTY_ERROR);
		}
		LOGGER.info(String.format(CREATE_MESSAGE, configPath));
		ApplicationStorage instance = new ApplicationStorage();
		instance.setApplicationContext(new ClassPathXmlApplicationContext(configPath));
		return instance;
	}

	private void setApplicationContext(ApplicationContext ctx)
	{
		context = ctx;
	}

	public ApplicationContext getApplicationContext()
	{
		return context;
	}

	public TemplateEntity getTemplateEntity(String name)
	{
		return (TemplateEntity) context.getBean(name, TemplateEntity.class);
	}

	public TemplatePojoEntity getTemplatePojoEntity(final String name)
	{
		return (TemplatePojoEntity) context.getBean(name, TemplatePojoEntity.class);
	}

}
